//
//  bigimagedb.m
//  tcpoctest
//
//  Created by gump on 4/8/13.
//  Copyright (c) 2013 gump. All rights reserved.
//

#import "bigimagedb.h"
#import "BigImageInfo.h"
#import "bigHeadImageDataSource.h"

@implementation bigimagedb

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:@"create table if not exists bigimage(mail text,\
url text,updatetime float)"];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM bigimage"];
    FMResultSet *s = [db executeQuery:strsql];
    
    [[DataControl shareControl].bigHIDS.bigimageDic removeAllObjects];
    
    while ([s next])
    {
        BigImageInfo *binfo = [[BigImageInfo alloc] init];
        binfo.mail = [s stringForColumn:@"mail"];
        binfo.url = [s stringForColumn:@"url"];
        binfo.updatetime = [s doubleForColumn:@"updatetime"];
        
        [[DataControl shareControl].bigHIDS.bigimageDic setObject:binfo
                                                    forKey:binfo.mail];
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertBigInfo:(BigImageInfo *)info
{
    if (db == nil) {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM bigimage WHERE mail = '%@'",info.mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    FMResultSet *s = [db executeQuery:strsql];
    if([s next])
    {
        strsql = [NSString stringWithFormat:@"update bigimage set url = '%@' \
updatetime = %f WHERE mail = '%@'",
                  info.url,
                  info.updatetime,
                  info.mail];
    }
    else
    {
        strsql = [NSString stringWithFormat:@"insert into bigimage(mail,url,updatetime) \
values('%@','%@',%f)",
                  info.mail,
                  info.url,
                  info.updatetime];
    }
    
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)deleteHImageByMail:(NSString *)mail
{
    if (db == nil) {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:@"DELETE FROM bigimage WHERE mail='%@'"
                        ,mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    [db executeUpdate:strsql];
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
